package com.example.myapplication11_4;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取按钮和TextView控件
        Button btnDatePicker = findViewById(R.id.btn_date_picker);
        TextView tvSelectedDate = findViewById(R.id.tv_selected_date);

        // 设置按钮点击事件，弹出日期选择对话框
        btnDatePicker.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance(); // 获取当前日期
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            // 创建DatePickerDialog，并设置初始日期和主题
            @SuppressLint("ResourceType") DatePickerDialog dialog = new DatePickerDialog(MainActivity.this, 3, (view, y, m, d) -> {
                // 选择日期后回调，显示所选日期
                String date = String.format("%d年%02d月%02d日", y, m + 1, d);
                tvSelectedDate.setText("选择的日期：" + date);
            }, year, month, day) {
                // 当日期变化时，实时更新对话框标题
                @Override
                public void onDateChanged(DatePicker view, int year, int month, int dayOfMonth) {
                    super.onDateChanged(view, year, month, dayOfMonth);
                    String title = String.format("%d年%02d月%02d日", year, month + 1, dayOfMonth);
                    setTitle(title);
                }
            };
            // 设置初始标题
            dialog.setTitle(String.format("%d年%02d月%02d日", year, month + 1, day));
            dialog.show(); // 显示对话框
        });
    }
}